#!/bin/bash
#
# fortune-zh  v1.2
# 
# Copyright (C) 2006 Zhang Le <robert.zhangle@gmail.com>
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

FORTUNE="/usr/bin/fortune"
CMD=`basename "$0"`

if [ -f $HOME/.fortune-zh.conf ]
then
	FILE=$(cat $HOME/.fortune-zh.conf)
else
	FILE="$@"
fi

for category in LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES \
	LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT \
	LC_IDENTIFICATION LC_ALL;
do
	if [ ! -z ${!category} ] 
	then 
		LANG="${!category}";
		break;
	fi
done

CHARSET=`echo ${LANG#*.} | tr A-Z a-z | sed -e 's/-//g'`

if test $CMD == "fortune-zh"; then
	case "$CHARSET" in
        big5)
                LC_ALL=zh_CN.GB18030 $FORTUNE $FILE | autob5
                ;;
        *)
                LC_ALL=$LANG $FORTUNE $FILE
                ;;
        esac
elif test $CMD == "fortune-sc"; then
	case "$CHARSET" in
	big5)
		echo 'Not available in BIG5 environment, try UTF-8'
		;;
	*)
		LC_ALL=$LANG $FORTUNE $FILE
		;;
	esac
elif test $CMD == "fortune-tc"; then
	case "$CHARSET" in
	gb*)
		echo 'Not available in GB environment, try UTF-8'
		;;
	big5)
		LC_ALL=zh_CN.GB18030 $FORTUNE $FILE | autob5 
		;;
	utf8)
		LC_ALL=zh_CN.GB18030 $FORTUNE $FILE | autob5 | autogb -i big5 -o utf8
		;;
	esac
fi
